/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.agi.util.sound;

import br.com.agi.util.geradordados.ManipuladorByte;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

/**
 *
 * @author Renato
 */
public class PlayerRealTime implements ManipuladorByte {
    private byte[] buf;
    
    private ManipuladorByte manipulador;
    private SourceDataLine source;
    private AudioFormat audioFormat;
    public PlayerRealTime(ManipuladorByte manipulador, AudioFormat audioFormat) throws LineUnavailableException{
        BuscadorDeFalantes buscador=new BuscadorDeFalantes(audioFormat);
        source=buscador.getLine();
        this.manipulador=manipulador;
        this.buf=manipulador.getBuf();
        this.audioFormat=audioFormat;
    }
    
    @Override
    public void setBuf(byte[] buf) {
        this.buf=buf;
    }

    @Override
    public void manipula(int off, int len) {
        manipulador.manipula(off, len);
        source.write(buf, off, len);          
    }
    
    
    
    public void play(int seconds) throws LineUnavailableException{

        int len=32;
        int times;
        times=(int)audioFormat.getFrameRate()/32;
        for(int t=0;t<seconds;t++){
            for(int i=0;i<times;i++){
                manipula(i*len,len);
            }
        }
        
    }
    
    
    @Override
    public byte[] getBuf(){
        return buf;
    }

    @Override
    public void open() throws Exception {
        source.open();
        source.start();
        this.manipulador.open();
    }

    @Override
    public void close() {
        this.manipulador.close();
        source.stop();
        source.close();
        
    }
}
